﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace RouterControl.Web
{
    public sealed class RouterControlWS2Factory : IDisposable
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(RouterControlWS2Factory));
        private ChannelFactory<IRouterControlWS2> _factory;

        public IRouterControlWS2 Channel
        {
            get { return _factory.CreateChannel(); }
        }

        public Uri Endpoint
        {
            get { return _factory.Endpoint.Address.Uri; }
        }

        public CommunicationState State
        {
            get { return _factory.State; }
        }

        public RouterControlWS2Factory()
        {
            _factory = new ChannelFactory<IRouterControlWS2>(
                new BasicHttpBinding()
                {
                    MaxReceivedMessageSize = (1024 * 1024), // 1MB
                    MaxBufferPoolSize = (8 * 1024 * 1024), // 8MB
                    OpenTimeout = new TimeSpan(0, 0, 10),   // 1 minute
                    CloseTimeout = new TimeSpan(0, 0, 10),  // 1 minute
                    ReceiveTimeout = new TimeSpan(0, 10, 0),// 10 minutes
                    SendTimeout = new TimeSpan(0, 10, 0),   // 10 minutes
                    MessageEncoding = WSMessageEncoding.Mtom,
                    TransferMode = TransferMode.Streamed,
                },
                new EndpointAddress(new Uri(Properties.Settings.Default.RouterControlWS2Endpoint))
                );

            _factory.Faulted += new EventHandler(factory_Faulted);

            _factory.Open();
        }

        private void factory_Faulted(object sender, EventArgs e)
        {
            _log.Warn("WCF client faulted");
        }

        public void Dispose()
        {
            if (_factory != null)
            {
                _factory.Close();
            }
        }

    }
}
